package http.get;

import annotation.Get;
import annotation.Path;
import annotation.Post;
import database.DBManager;

import spark.Request;
import spark.Response;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by LeoLu on 2017/3/16.
 */
@Path("/g/reqCheckDiscountCode")
public class ReqCheckDiscountCode extends BaseRequest {

    @Post
    public Object callAnyRespone(Request request, Response response) {

        String discountCode =  request.queryParams("discountCode");
        String md5Token = request.queryParams("userId");
        String time = request.queryParams("time");

        boolean result =  queryCodeStatus(discountCode);
        return result == true? codeSuccess() : codeFiled();//查询优惠码是不是在数据库里面的
    }

    /**
     * 更新优惠码的状态
     * @param code
     * @return
     */
    private boolean updateCodeStatus(String code){
        String sql = "update freecode set code_status=1 where discount_code=" + code;
        try {
            DBManager.getInstance().getPreStatement(sql).execute();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 优惠码失效
     * @return
     */
    private String codeFiled(){
        return universalResp("优惠码无效","500");
    }


    /**
     * 优惠码成功
     * @return
     */
    private String codeSuccess(){
        return universalResp("OK","200");
    }

    /**
     * 查询code是否匹配数据库
     * @param code
     * @return
     */
    private boolean queryCodeStatus(String code){
        System.out.println("code-->" + code);
        String sql  = "select * from freecode where discount_code="+code;
        System.out.println("-->" + sql);
        PreparedStatement statement = DBManager.getInstance().getPreStatement(sql);
        try {
            ResultSet resultSet = statement.executeQuery();
            boolean result = resultSet.next();
            System.out.println("-->" + result);
            if (!result) return result;
            while(result) {
                int code_status =  resultSet.getInt("code_status");
                System.out.println("code:" + code_status);
                return result = code_status==0? updateCodeStatus(code) : false;
            }
        } catch (SQLException e) {
            System.out.print(e);
            e.printStackTrace();
        }
        return false;
    }
}
